"""
管理端用户模型
"""
from sqlalchemy import Column, Integer, String, DateTime
from werkzeug.security import generate_password_hash, check_password_hash
from datetime import datetime
from extension import db


class User(db.Model):
    """用户表（管理端）"""
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    username = Column(String(50), unique=True, nullable=False, comment='用户名')
    password_hash = Column(String(256), nullable=False, comment='密码哈希')
    full_name = Column(String(50), nullable=False, comment='姓名')
    email = Column(String(50), comment='电子邮箱')
    created_at = Column(DateTime, default=datetime.utcnow, comment='创建时间')
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, comment='更新时间')

    def set_password(self, password):
        """设置密码"""
        self.password_hash = generate_password_hash(password)

    def verify_password(self, password):
        """验证密码"""
        return check_password_hash(self.password_hash, password)
    
    def to_dict(self, include_password=False):
        """转换为字典"""
        result = {
            'id': self.id,
            'username': self.username,
            'fullName': self.full_name,
            'email': self.email,
            'createdAt': self.created_at.strftime('%Y-%m-%d %H:%M:%S') if self.created_at else None,
            'updatedAt': self.updated_at.strftime('%Y-%m-%d %H:%M:%S') if self.updated_at else None
        }
        
        # 通常不包含密码哈希
        if include_password:
            result['passwordHash'] = self.password_hash
        
        return result
    
    @classmethod
    def from_dict(cls, data):
        """从字典创建实例"""
        user = cls(
            username=data.get('username'),
            full_name=data.get('fullName'),
            email=data.get('email', '')
        )
        if 'password' in data:
            user.set_password(data['password'])
        return user
    
    def update_from_dict(self, data):
        """从字典更新实例"""
        if 'username' in data:
            self.username = data['username']
        if 'fullName' in data:
            self.full_name = data['fullName']
        if 'email' in data:
            self.email = data['email']
        if 'password' in data:
            self.set_password(data['password'])
        return self

